package com.yunbai.yunbaigrowup.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolygonOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.example.yunbaigrowup.R;
import com.yunbai.yunbaigrowup.activity.CallBackActivity;
import com.yunbai.yunbaigrowup.activity.ChooseChildrean;
import com.yunbai.yunbaigrowup.activity.Geofance_Activity;
import com.yunbai.yunbaigrowup.control.BtnActionListnerBrige;
import com.yunbai.yunbaigrowup.control.ToggleBrige;
import com.yunbai.yunbaigrowup.impl.CheckInternet;
import com.yunbai.yunbaigrowup.impl.GetBatteryInfoImpl;
import com.yunbai.yunbaigrowup.impl.GetFollowPosImpl;
import com.yunbai.yunbaigrowup.impl.Get_UploadGeoInfoImpl;
import com.yunbai.yunbaigrowup.impl.SendOrderToServer;
import com.yunbai.yunbaigrowup.interfacer.GetBatteryInfoInterfaces;
import com.yunbai.yunbaigrowup.interfacer.OnDrawAreaListener;
import com.yunbai.yunbaigrowup.model.Battery_signal_data;
import com.yunbai.yunbaigrowup.model.Battery_signal_model;
import com.yunbai.yunbaigrowup.model.ConvertPointInof;
import com.yunbai.yunbaigrowup.model.LocationMsg;
import com.yunbai.yunbaigrowup.model.PointInfo;
import com.yunbai.yunbaigrowup.task.GetHisTask;
import com.yunbai.yunbaigrowup.utils.Common;
import com.yunbai.yunbaigrowup.utils.CommonUtil;
import com.yunbai.yunbaigrowup.utils.ConverterGPS;
import com.yunbai.yunbaigrowup.utils.DialogManager;
import com.yunbai.yunbaigrowup.utils.LogUtils;
import com.yunbai.yunbaigrowup.utils.NetworkUtils;
import com.yunbai.yunbaigrowup.utils.PointUtils;
import com.yunbai.yunbaigrowup.utils.SQLTools;
import com.yunbai.yunbaigrowup.utils.SharePreferenceUtils;
import com.yunbai.yunbaigrowup.activity.FingerView.Position;

/**
 * app主界面，显示地图
 * @author YJ
 *
 */
public class Fragment_Content extends Fragment implements OnClickListener {

    private final static String  TAG = "Fragment_Content";
	private View layout;
	private MapView mMapView;
	private BaiduMap mBaiduMap;
	private Button btn_menu;
	private Button ok, cancel;
	private TextView tv_child_name;
	private LinearLayout geofance;
	// 定位相关
	private LocationClient mLocClient;
	private LocationMode mLocMode;
	private final static int MSG_GETGEO_OK = 0X999;


	private int flags = -1;// 循环从服务器读取数据
	// 地图标记物
	private Marker mMarker;
	private InfoWindow mInfoWindow;
	// 初始化全局 bitmap 信息，不用时及时 recycle
	BitmapDescriptor bdA = BitmapDescriptorFactory
			.fromResource(R.drawable.icon_marka);
	BitmapDescriptor bdB = BitmapDescriptorFactory
			.fromResource(R.drawable.loc_geo);
	private Timer timer;//跟踪的计时器
	private Timer battery_single_timer;//获取电池和信号的信号的计时器；
	private SharePreferenceUtils sp;
	// 绑定的手表号码
	String deviceNmuber = null;
	//修改电量图标
	private MyBroadcast broadcast;
	public static  boolean getBattInfo = true;
	private GetBatteryInfoInterfaces getBaImpl;

	public static List<ConvertPointInof> convertpos ;
	private ImageView iv_battey,iv_signal;
	
	private SQLTools sqlTools;
	ArrayList<LatLng> geo_points;//围栏信息点的信息
    static Boolean show_geo = false;
    //保存直线点的信息
     List<LatLng> lineList;
     public static boolean IS_FOLLOW = false;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		layout = inflater.inflate(R.layout.fragment_map, null);
		return layout;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		sp = SharePreferenceUtils.getInstance(getActivity());
		initCompoent();
		sqlTools = SQLTools.newInstance(getActivity());
		mBaiduMap = mMapView.getMap();
		mMapView.removeViewAt(2);// 去掉地图上的小控件
		mMapView.removeViewAt(1);
		MarkClickLisetner("");//标记物的监听
		lineList = new ArrayList<LatLng>() ;
		lineList.clear();
		convertpos = new ArrayList<ConvertPointInof>();//存放转换后的经纬度和时间
		BtnActionListnerBrige.getInstances().setActionListner(actionListner);
		//30秒一上传数据
		if (NetworkUtils.isNetConnected(getActivity())||NetworkUtils.isWifiConnected(getActivity())
				||NetworkUtils.is3gConnected(getActivity())) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					String content ="#SGPS#" + "30" + "#" ;
					new SendOrderToServer(getActivity(), null).setOrder2Watch(content);
				}
			}).start();
		}else{
			CommonUtil.showMsg(getActivity(), "网络连接不可用");
		}
		deviceNmuber = sp.readString("tsim");
		if (sp.readString("tsim").equals("")) {
			CommonUtil.showMsg(getActivity(), "当前账号没有绑定手表sim卡");
		}
		
		//注册修改电量信息的广播
		broadcast = new MyBroadcast();
		IntentFilter filter = new IntentFilter();
		filter.addAction("MY_RECIVIER_ACTION");
		getActivity().registerReceiver(broadcast, filter);
		//获取电池信号等信息
		getWatchbattery_single_info();
		
	}
	/**
	 * 获取电池和信号信息
	 */
	public void getWatchbattery_single_info(){
		if (NetworkUtils.isNetConnected(getActivity())||NetworkUtils.isWifiConnected(getActivity())
				||NetworkUtils.is3gConnected(getActivity())) {
			battery_single_timer = new Timer();
			battery_single_timer.schedule(new TimerTask() {
				
				@Override
				public void run() {
					String token = sp.readString("token");
					String imei = sp.readString("currentimei");
					new GetBatteryInfoImpl(getActivity()).getBatteryInfo(token,imei);
				}
			}, 0, 10 * 1000);
		}
	}
	/**
	 * 检测手表是否联网
	 */
	CheckInternet.GetInternetStatListner getInternetStatListner = new CheckInternet.GetInternetStatListner() {
		@Override
		public void OnGetInterStat(Object o) {
			Message s = new Message();
			s.what = Common.WATCH_INTERNET;
			s.obj = o;
			mHandler.sendMessage(s);
		}
	};
	
	
	// 获取服务器的历史围栏
		Get_UploadGeoInfoImpl.OnGetGeoListner getGeoListner = new Get_UploadGeoInfoImpl.OnGetGeoListner() {

			@Override
			public void OnSuccess(Object o) {

				Log.e("m_geo", "从服务器得到的的围栏的信息" + o.toString());

				Message s = new Message();
				s.what = MSG_GETGEO_OK;
				s.obj = o;
				mHandler.sendMessage(s);
			}

			@Override
			public void OnFail(Object o) {
				// TODO Auto-generated method stub
                if(o!=null){

					
                }
			}

		};
	
		
	//菜单按钮的点击
	BtnActionListnerBrige.btnActionListner actionListner = new BtnActionListnerBrige.btnActionListner() {

		@Override
		public void btnClicked(int opt) {
			switch (opt) {
			case Common.BTN_GEO://围栏
				show_geo = !show_geo;
				if (show_geo) {
					geo_points = new ArrayList<LatLng>();
					Common.SHOW_DIALOG = true;
					geo_points = CommonUtil.getFanceInfo(sp, sqlTools);
					LogUtils.e(TAG, "--->查询围栏:"+geo_points.size());
					//获取得到的围栏信息不为空
					if (geo_points.size()!=0) {
						drawArea(geo_points);
					}else{
						//从服务器中获取数据
						new Thread(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								new Get_UploadGeoInfoImpl(getActivity(),
										getGeoListner).getGeoInfo("");
							}
						}).start();
						
						
					}
				}else{
				
					if(geo_points.size()!=0){
						AlertDialog a  = new AlertDialog.Builder(getActivity())
						.setTitle("是否继续开启围栏？")
						.setPositiveButton("开启", new DialogInterface.OnClickListener() {
			
							@Override
							public void onClick(DialogInterface dialog, int which) {
								Common.SHOW_DIALOG = true;//弹窗警告
								mMapView.getMap().clear();
								firstLoc();
							}
						})
						.setNegativeButton("不开启", new DialogInterface.OnClickListener() {
			
							@Override
							public void onClick(DialogInterface dialog, int which) {
								Common.SHOW_DIALOG = false;
								mMapView.getMap().clear();
								firstLoc();
								}
							})
						.setCancelable(false)
						.create();
						a.show();
						//设置是否是从打开围栏，跳转到绘制围栏界面
						Common.OPEN_DRAW_FANCE = false;
					}
					
				}
				
				break;
			case Common.BTN_LISTNER_HIS:// 历史记录
				// 滚轮时间选择
				Calendar c = Calendar.getInstance();
				new DatePickerDialog(getActivity(),
						new DatePickerDialog.OnDateSetListener() {

							@Override
							public void onDateSet(DatePicker view, int year,
									int monthOfYear, int dayOfMonth) {
								// TODO Auto-generated method stub
								// 开启线程或者异步任务下载数据
								String token = sp.readString("token");
								String imei = sp.readString("currentimei");
								String startTime = year + "-"
										+ (monthOfYear + 1) + "-" + dayOfMonth
										+ "-" + 00 + ":" + 00;
								String endTime = year + "-" + (monthOfYear + 1)
										+ "-" + dayOfMonth + "-" + 23 + ":"
										+ 00;
								mMapView.getMap().clear();
								new GetHisTask(mHandler).execute(token, imei,
										startTime, endTime);

							}
						}, c.get(Calendar.YEAR), c.get(Calendar.MONTH),
						c.get(Calendar.DAY_OF_MONTH)).show();
				break;
			case Common.BTN_LISTNER_CURPOS_FOLLOW:// 跟踪
				IS_FOLLOW = !IS_FOLLOW;
				mMapView.getMap().clear();
				flags = flags * -1;
				startCurrentLoc();
				if (flags < 0) {
					timer.cancel();
					mMapView.getMap().clear();
					CommonUtil.showMsg(getActivity(), "关闭定位跟踪!");
					lineList.clear();//清除保存绘制的直线的点的信息
					firstLoc();
				} else {
					CommonUtil.showMsg(getActivity(), "开启跟踪定位");
				}
				break;
			case Common.BTN_CALLBACK://回拨
				startActivity(new Intent(getActivity(),CallBackActivity.class));
				break;
			}

		}
	};
	/**
	 * 第一次进来显示小孩的位置
	 */
	public void firstLoc() {
		clearMap();
		if (NetworkUtils.isNetConnected(getActivity())||NetworkUtils.isWifiConnected(getActivity())
				||NetworkUtils.is3gConnected(getActivity())) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					LogUtils.e(TAG, "sp读到的token" + sp.readString("token"));
					LogUtils.e(TAG, "当前定位的IMEI：" + sp.readString("currentimei"));
					String token = sp.readString("token");
					String imei = sp.readString("currentimei");
					new GetFollowPosImpl(getCurPosListner).getCurrentPos(token,
							imei);
				}
			}).start();
		}else{
			CommonUtil.showMsg(getActivity(), "网络连接不可用");
		}
	}

	
	/**
	 * 开启跟踪
	 */
	public void startCurrentLoc() {
		timer = new Timer();
		if (NetworkUtils.isNetConnected(getActivity())||NetworkUtils.isWifiConnected(getActivity())
				||NetworkUtils.is3gConnected(getActivity())) {
			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					if (flags > 0) {
						String token = sp.readString("token");
						String imei = sp.readString("currentimei");
						new GetFollowPosImpl(getCurPosListner).getFollowPos(token,
								imei);
					}
				}
			}, 0, 10 * 1000);//每10s获取一次数据
		}else{
			CommonUtil.showMsg(getActivity(), "网络连接不可用");
		}
	}

	// 获取当前位置和实时跟踪的回调接口
	GetFollowPosImpl.onGetCurrentPosListner getCurPosListner = new GetFollowPosImpl.onGetCurrentPosListner() {

		@Override
		public void onGetCurrntPosSuccess(Object o, int opt) {
			switch (opt) {
			case Common.GET_FOLLOW_POS://跟随
				PointInfo followPos = JSON.parseObject((String) o,
						PointInfo.class);
				List<LocationMsg> followList = followPos.getData();
				if (followList.get(0).getLon()!=null) {
					
					MapStatusUpdate ss1 = MapStatusUpdateFactory.zoomTo(16);
					//mBaiduMap.setMapStatus(ss1);
					mBaiduMap.animateMapStatus(ss1);
					showIconOnMap(followPos);
				}else{
					flags = flags*-1;
					mHandler.sendEmptyMessage(0x956);
				}
				break;
			case Common.GET_CURRENT_POS://当前最新位置
				PointInfo currentPos = JSON.parseObject((String) o,
						PointInfo.class);
				List<LocationMsg> locList = currentPos.getData();
				if (locList.get(0).getLon()!=null) {
					double longtitude = Double.valueOf(locList.get(0).getLon());
					double latotide = Double.valueOf(locList.get(0).getLat());
					//保存当前手表最新的经纬度信息
					sp.saveString("current_lat", String.valueOf(latotide));
					sp.saveString("current_lng", String.valueOf(longtitude));
					LatLng point = ConverterGPS.conGPS(new LatLng(latotide,
							longtitude));
					//判断小孩是否在围栏内
					ArrayList<LatLng> geoList = CommonUtil.getFanceInfo(sp, sqlTools);
					if (geoList.size()!=0) {
						int index = PointUtils.isPointInArea(point, geoList);
						Message s = new Message();
						if (index==1) {
							//在里面
							s.what = Common.SHOW_DIALOG_IN;
							mHandler.sendMessage(s);
						}else if (index == -1) {
							//在外面
							s.what = Common.SHOW_DIALOG_OUT;
							mHandler.sendMessage(s);
						}else if (index ==0) {
							//在边上
							s.what =Common.SHOW_DIALOG_ON;
							mHandler.sendMessage(s);
						}
					}
					addCircleToMap(point, 100);
					MapStatusUpdate ss = MapStatusUpdateFactory.newLatLngZoom(
							point, 16);
					//mBaiduMap.setMapStatus(ss);
					
					
					mBaiduMap.animateMapStatus(ss);
					showIconOnMap(currentPos);
				}else{
					mHandler.sendEmptyMessage(0x956);
				}
				break;
			}

		}

		@Override
		public void onGetCurrntPosFail(Object o, int opt) {
			JSONObject json = JSON.parseObject((String) o);
			
			Message s = new Message();
			s.what = 0x3895;
			mHandler.sendMessage(s);
		}
	};

	private void initCompoent() {
		tv_child_name = (TextView) layout.findViewById(R.id.textView1);
		btn_menu = (Button) layout.findViewById(R.id.menu);
		mMapView = (MapView) layout.findViewById(R.id.mapView);
		ok = (Button) layout.findViewById(R.id.ok);
		cancel = (Button) layout.findViewById(R.id.cancel);
		iv_battey = (ImageView) layout.findViewById(R.id.battery);
		iv_signal = (ImageView) layout.findViewById(R.id.signal);
		btn_menu.setOnClickListener(this);
	

	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			//修改小孩的名字
			String index= sp.readString("current_child_index");
			String name = sp.readString("child_name"+index);
			tv_child_name.setText(name);
			switch (msg.what) {
			case Common.ASY_HIS_OK:
				PointInfo hisInfo = (PointInfo) msg.obj;
				if (hisInfo.getStatus() == 0) {
					if (hisInfo.getData().size() == 1) {
						CommonUtil.showMsg(getActivity(), "没有这个时间段的历史记录");
						firstLoc();
					} else {
						MapStatusUpdate ss = MapStatusUpdateFactory.zoomTo(14);
						mBaiduMap.animateMapStatus(ss);
						showIconOnMap(hisInfo);
					}

				} else {
					CommonUtil.showMsg(getActivity(), "没有这个时间段的历史记录");
					firstLoc();
				}
				break;
			case 0x956:
				//清除最新位置的信息
				sp.saveString("current_lat", "");
				sp.saveString("current_lng", "");
				CommonUtil.showMsg(getActivity(), "没有最新位置信息");
				break;
			case Common.BATTERY_SIGNAL_INFO_OK:
				Battery_signal_model bas_info = (Battery_signal_model) msg.obj;
				List<Battery_signal_data> basinfo_list = bas_info.getData();
				//电压等级(0:无电 2:弱电报警 3:低电可用 4:电量中 5:电量高 6:电量满)
				if (basinfo_list.get(0).getEnergy().equals("6")) {
					iv_battey.setImageResource(R.drawable.stat_sys_battery_100);
				}else if(basinfo_list.get(0).getEnergy().equals("5")){
					iv_battey.setImageResource(R.drawable.stat_sys_battery_80);
				}else if(basinfo_list.get(0).getEnergy().equals("4")){
					iv_battey.setImageResource(R.drawable.stat_sys_battery_50);
				}else if(basinfo_list.get(0).getEnergy().equals("3")){
					iv_battey.setImageResource(R.drawable.stat_sys_battery_20);
				}else if(basinfo_list.get(0).getEnergy().equals("0")){
					iv_battey.setImageResource(R.drawable.stat_sys_battery_0);
				}
				//信号强度(0:无信号 1:信号差 2:信号弱 3:信号良 4:信号优)
				if (basinfo_list.get(0).getSignal().equals("4")) {
					iv_signal.setImageResource(R.drawable.stat_sys_wifi_signal_4);
				}else if(basinfo_list.get(0).getSignal().equals("3")){
					iv_signal.setImageResource(R.drawable.stat_sys_wifi_signal_3);
				}else if(basinfo_list.get(0).getSignal().equals("2")){
					iv_signal.setImageResource(R.drawable.stat_sys_wifi_signal_2);
				}else if(basinfo_list.get(0).getSignal().equals("1")){
					iv_signal.setImageResource(R.drawable.stat_sys_wifi_signal_1);
				}else if(basinfo_list.get(0).getSignal().equals("0")){
					iv_signal.setImageResource(R.drawable.stat_sys_wifi_signal_0);
				}
				break;
			case Common.WATCH_INTERNET:
				LogUtils.e(TAG, "手表是否上网返回的数据"+(String)msg.obj);
				JSONObject jsonObject = JSONObject.parseObject((String)msg.obj);
				String status = jsonObject.getString("status");
				String msgs = jsonObject.getString("msg");
				if (!status.equals("0")&&!msgs.equals("Term Online!")) {
					LogUtils.e(TAG, "手表不在线,正在等待手表上网");
					//Toast.makeText(getActivity(), "手表不在线,正在等待手表上网！", 10000).show();
					AlertDialog dialog = new AlertDialog.Builder(getActivity())
					.setTitle("提醒")
					.setMessage("手表不在线，正在等待手表上网\n是否继续提醒")
					.setCancelable(false)
					.setPositiveButton("提醒", null)
					.setNegativeButton("不提醒", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Common.NOTICE_OFFLINE = false;
						}
					})
					.create();
					if(Common.NOTICE_OFFLINE ){
						dialog.show();
						//发短信给手表，打开GPRS
						String deviceNmuber = sp.readString("tsim");
						LogUtils.e(TAG, "发送短信给手表打开GPRS："+deviceNmuber);
						if (!deviceNmuber.equals("")) {
							String context = "#SGPS#"+"30"+"#";
							if (CommonUtil.isPhoneNum(deviceNmuber)) {
								CommonUtil.sendSms(deviceNmuber, context);
							}else{
								CommonUtil.showMsg(getActivity(), "手表号码格式错误，发送短信失败！");
							}
						}else{
							CommonUtil.showMsg(getActivity(), "沒有綁定号码");
						}
					}
					
				}else{
					LogUtils.e(TAG, "手表在线");
				}
				break;
				
			case Common.SHOW_DIALOG_IN:
				LogUtils.e(TAG, "对象在围栏内");
				if (Common.SHOW_DIALOG) {
					//DialogManager.showNormalDialog("小孩在围栏里面", getActivity());
				}
				break;
			case Common.SHOW_DIALOG_ON:
				if (Common.SHOW_DIALOG) {
					DialogManager.showNormalDialog("越界警告", getActivity());
				}
				break;
			case Common.SHOW_DIALOG_OUT:
				if (Common.SHOW_DIALOG) {
					DialogManager.showNormalDialog("越界报警", getActivity());
				}
				break;
			case 0x3895:
				CommonUtil.showMsg(getActivity(), "获取最新位置失败");
				break;
			case MSG_GETGEO_OK:
				ArrayList<LatLng> locationList = null;
		
				LogUtils.e(TAG, "" + msg.obj);
				JSONObject jobj = JSONObject.parseObject((String) msg.obj);
				JSONArray array = jobj.getJSONArray("data");
				if (array.size() == 0) {
					//CommonUtil.showMsg(getActivity(), "很遗憾，没有您的围栏记录..");
					AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
					builder.setTitle("提醒");
					builder.setMessage("您还没有添加围栏,是否现在添加？");
					builder.setNegativeButton("返回", null);
					builder.setCancelable(false);
					builder.setPositiveButton("添加", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Common.OPEN_DRAW_FANCE = true;
							//跳转到绘制围栏界面
							startActivity(new Intent(getActivity(),Geofance_Activity.class));
						}
					});
					builder.create().show();
				} else {

					JSONObject json_pos = JSON.parseObject(array.get(0)
							.toString());

					JSONArray array_poly = json_pos.getJSONArray("poly");

					JSONObject loc = JSON.parseObject(array_poly.get(0)
							.toString());

					String pos = loc.getString("pos");

					Log.e("m_tag", "pos服务器中返回的围栏的数据" + pos);
					locationList = new ArrayList<LatLng>();
					// 拆分逗号
					String[] pos_array = pos.split(",");
					for (int i = 0; i < pos_array.length; i++) {

						if (i + 1 != pos_array.length) {
							LatLng l = new LatLng(
									Double.parseDouble(pos_array[i]),
									Double.parseDouble(pos_array[i + 1]));

							locationList.add(l);
						}

						i = i + 1;

					}
				}
				if (locationList != null) {
					// 画围栏
					drawArea(locationList);

					// 将围栏的信息保存到本地
					// 如果表中有数据，就清除数据
					String index_1 = sp.readString("current_child_index");
					sqlTools.deleteLatlng(sp.readString("phoneNum") + index_1);
					LogUtils.e(TAG, "插入数据到：" + sp.readString("phoneNum")
							+ index_1);
					for (int i = 0; i < locationList.size(); i++) {
						String lon = String
								.valueOf(locationList.get(i).longitude);
						String lat = String
								.valueOf(locationList.get(i).latitude);
						sqlTools.insertLatlng(lon, lat,
								sp.readString("phoneNum") + index_1);
					}
				}
				break;

			}
		};
	};
	

	
	/**
	 * 在地图上把点绘制出来
	 * 
	 * @param info
	 */
	private LatLng desLatLng;//保存新的一个点的信息
	private void showIconOnMap(PointInfo info) {
		convertpos.clear();//清空之前存放的数据
		List<LocationMsg> locList = info.getData();//保存了时间信息的链表，但是没有纠偏
		// 显示图标的个数
		List<LatLng> lalnList = new ArrayList<LatLng>();
		for (int i = 0; i < locList.size(); i++) {
			double longtitude = Double.valueOf(locList.get(i).getLon());
			double latotide = Double.valueOf(locList.get(i).getLat());
			lalnList.add(new LatLng(latotide, longtitude));
		}
		//gps纠偏
		for (int i = 0; i < lalnList.size(); i++) {
			LatLng desLatLng = ConverterGPS.conGPS(lalnList.get(i));
			lineList.add(desLatLng);
			convertpos.add(new ConvertPointInof(desLatLng,locList.get(i).getTime()));//纠偏的gps
			OverlayOptions ooA = new MarkerOptions().position(desLatLng)
					.icon(bdA).zIndex(9).draggable(true);
			Marker mMarkerA = (Marker) (mBaiduMap.addOverlay(ooA));
		}
		if (IS_FOLLOW) {
			if (lineList.size()!=0) {
				Log.e(TAG, "直线的点"+lineList.size());
				//判断两个点之间的距离，然后划线
				OverlayOptions ooL = new PolylineOptions().points(lineList).color(0x3300FF00);
			}
		}
	}

	/**
	 * 在地图上添加圆圈
	 */
	public void addCircleToMap(LatLng laln, int radius) {
		// 添加圆
		LatLng llCircle = laln;
		OverlayOptions ooCircle = new CircleOptions().fillColor(0x3300FF00)
				.center(llCircle).stroke(new Stroke(5, 0x3300FF00))
				.radius(radius);// 半径为1000
		mBaiduMap.addOverlay(ooCircle);
	}

	/**
	 * 取消画圈圈
	 */
	public void clearClick() {
		// 清除所有图层
		mMapView.getMap().clear();
	}
	
	/**
	 * 画围栏
	 * 
	 * @param list
	 */
	private void drawArea(ArrayList<LatLng> points){
		LogUtils.e(TAG, "绘制围栏");
		//clearMap();//清除图层
		OverlayOptions ooPolygon = new PolygonOptions().points(points)
				.stroke(new Stroke(5, 0xAA00FF00)).fillColor(0xAAFFFF00);
		mBaiduMap.addOverlay(ooPolygon);
	}
	
	private void clearMap(){
		mMapView.getMap().clear();
	}
	/**
	 * 标记物点击事件
	 */
	public void MarkClickLisetner(final String time){
		mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {
			@Override
			public boolean onMarkerClick(final Marker marker) {
				Button button = new Button(getActivity().getApplicationContext());
				button.setBackgroundResource(R.drawable.popup);
				OnInfoWindowClickListener listener = null;
				//弹出框点击事件
				listener = new OnInfoWindowClickListener() {
					public void onInfoWindowClick() {
						mBaiduMap.hideInfoWindow();
					}
				};
				//标记物的经纬度
				LatLng ll = marker.getPosition();
				for (int i = 0; i < convertpos.size(); i++) {
					if (ll.latitude==convertpos.get(i).getConvertPoint().latitude
							&&ll.longitude==convertpos.get(i).getConvertPoint().longitude) {
						button.setText(convertpos.get(i).getTime());
						button.setTextColor(Color.BLACK);
						mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(button), ll, -50, listener);
						mBaiduMap.showInfoWindow(mInfoWindow);
						break;
					}
				}
				return true;
			}});
			
		
	}
	/**
	 * 取消标记物点击事件
	 */
	public void cancelMarkerListener(){
		mBaiduMap.setOnMarkerClickListener(null);
	}
	/**
	 * 点击事件的监听
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.menu://菜单
			if (!show_geo) {
				mMapView.getMap().clear();
				firstLoc();
			}
			ToggleBrige toggle = ToggleBrige.getInstance();
			toggle.doMeth();
			break;
		}
	}
	/**
	 * 信号和电量的广播
	 * @author YJ
	 *
	 */
	public class MyBroadcast extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals("MY_RECIVIER_ACTION")) {
				//改变电量的图标
				Bundle data =  intent.getExtras();
				String batsig_info = (String) data.get("info");
				//修改图标
				Battery_signal_model bsm =  JSONObject.parseObject(batsig_info, Battery_signal_model.class);
				if (!bsm.getData().get(0).getWarn().equals("No fit record")) {
					Message s = new Message();
					s.what  = Common.BATTERY_SIGNAL_INFO_OK;
					s.obj = bsm;
					mHandler.sendMessage(s);
				}
			}
			
		}
		
	}
	@Override
	public void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	public void onResume() {
		mMapView.onResume();
		firstLoc();
		LogUtils.e(TAG, "地图界面onResume");
		if (Common.OPEN_DRAW_FANCE ) {
			 geo_points= CommonUtil.getFanceInfo(sp, sqlTools);
			LogUtils.e(TAG, "--->查询围栏onResume:"+geo_points.size());
			//获取得到的围栏信息不为空
			if (geo_points.size()!=0) {
				drawArea(geo_points);
				Common.OPEN_DRAW_FANCE=false;
			}
		}
		//查询手表是否联网，没有联网就发短信联网
				if (NetworkUtils.isNetConnected(getActivity())||NetworkUtils.isWifiConnected(getActivity())
						||NetworkUtils.is3gConnected(getActivity())) {
					new Thread(new Runnable() {
						
						@Override
						public void run() {
							String token = sp.readString("token");
							String imei = sp.readString("currentimei");
							new CheckInternet(getInternetStatListner).getWatchInterStat(token, imei);
						}
					}).start();
				}else{
					CommonUtil.showMsg(getActivity(), "网络连接不可用");
				}
		super.onResume();
	}

	@Override
	public void onDestroy() {
		// 退出时销毁定位
		mLocClient.stop();
		// 关闭定位图层
		mBaiduMap.setMyLocationEnabled(false);
		mMapView.onDestroy();
		mMapView = null;
		battery_single_timer.cancel();
		getActivity().unregisterReceiver(broadcast);
		super.onDestroy();
	}

}
